package com.ulook.planetmanager.ui.dashboard;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;
import com.ulook.planetmanager.R;
import com.ulook.planetmanager.base.BaseFragment;
import com.ulook.planetmanager.base.BaseRecyclerAdapter;
import com.ulook.planetmanager.base.BaseViewHolder;
import com.ulook.planetmanager.model.VArticlePreInfo;
import com.ulook.planetmanager.util.StringUtil;
import com.ulook.planetmanager.widget.ArticleView;

public class DashboardFragment extends BaseFragment {

    private DashboardViewModel viewModel;
    private View root;
    private QMUITopBarLayout topBar;
    private QMUIPullLayout pullLayout;
    private RecyclerView recyclerView;
    private int currUserId;
    private BaseRecyclerAdapter<VArticlePreInfo> mAdapter;
    private boolean isRefresh;
    private EditText search;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(this).get(DashboardViewModel.class);
        root = inflater.inflate(R.layout.fragment_dashboard, container, false);

        // 消息提示
        viewModel.getToastText().observe(getViewLifecycleOwner(), s -> {
            Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
        });

        // 推荐动态
        viewModel.getLoadData().observe(getViewLifecycleOwner(), loadDataList ->{
            if(isRefresh){
                mAdapter.setData(loadDataList);
                recyclerView.scrollToPosition(0);
            }else {
                mAdapter.append(loadDataList);
            }
        });

        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 获取数据， 初始化
        // currUserId = ((MainActivity)getActivity()).getCurrUser().getId();
        initTopBar();
        initData();
    }

    /**
     * 初始化顶部导航栏
     */
    private void initTopBar(){
        QMUIStatusBarHelper.translucent(getActivity());
        topBar = root.findViewById(R.id.square_bar);
        topBar.setTitle(getString(R.string.title_square));
    }

    /**
     * 初始化页面动态
     */
    private void initData(){

        search = root.findViewById(R.id.main_article_search);
        Button bt = root.findViewById(R.id.main_article_search_bt);
        bt.setOnClickListener(view -> {
            String s = search.getText().toString();
            if(!StringUtil.isEmpty(s)){
                viewModel.loadData(s, 0);
            }
        });

        // 推荐动态
        pullLayout = root.findViewById(R.id.squ_pull_layout);
        recyclerView = root.findViewById(R.id.squ_recyclerView);

        // 监听 上拉/下拉 动作
        pullLayout.setActionListener(pullAction -> pullLayout.postDelayed(() -> {
            String s = search.getText().toString();
            if(!StringUtil.isEmpty(s)){
                if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                    isRefresh = true;
                    viewModel.loadData(s, 0);
                } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                    isRefresh = false;
                    viewModel.loadData(s, mAdapter.getItemCount());
                }
            }
            pullLayout.finishActionRun(pullAction);
        }, 3000));
        // 设置布局
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });
        // 初始化Adapter
        mAdapter = new BaseRecyclerAdapter<VArticlePreInfo>(getContext(), null) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.recycler_article;
            }
            @Override
            public void bindData(BaseViewHolder holder, int position, VArticlePreInfo item) {
                ArticleView articleView = holder.getItemView(R.id.recycler_article_view);
                articleView.setWidgetData(item, currUserId);
            }
        };
        // 添加item点击动作
        /*mAdapter.setOnItemClickListener((itemView, pos) -> {
            VArticlePreInfo articlePreInfo = mAdapter.getItem(pos);
            // 删除记录
            viewModel.delete(articlePreInfo.getUid(), pos);
            mAdapter.remove(pos);
            // 跳转详情页面
            *//*Intent intent = new Intent(getActivity(), ArticleActivity.class);
            intent.putExtra("currUserId", currUserId);
            intent.putExtra("article", articlePreInfo);
            startActivity(intent);*//*
        });*/
        // item长按动作
        mAdapter.setOnItemLongClickListener((itemView, pos) -> {
            // 弹框提醒
            new QMUIDialog.MessageDialogBuilder(getActivity())
                    .setTitle("删除")
                    .setMessage("确定要删除这条动态吗？")
                    .addAction("取消", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            viewModel.delete(mAdapter.getItem(pos).getUid(), pos);
                            mAdapter.remove(pos);
                            dialog.dismiss();
                        }
                    })
                    .show();
        });
        recyclerView.setAdapter(mAdapter);
        String s = search.getText().toString();
        if(!StringUtil.isEmpty(s)){
            viewModel.loadData(s, 0);
        }
    }
}